package server.unit;

import server.proxy.ClientListener;
import server.proxy.Receiverable;

import java.io.*;
import java.net.Socket;

public class Client {
    public static final String DEFAULT_NAME = "1";

    private Socket socket;
    private ClientListener clientListener;
    private DataInputStream in;
    private DataOutputStream out;
    private String nickName;
    private String lobby;
    private Receiverable receiverable;

    public Client(Socket clientSocket, Receiverable receiverable) throws IOException {
        this.receiverable = receiverable;
        this.socket = clientSocket;
            in = new DataInputStream(
                    socket.getInputStream());
            out = new DataOutputStream(socket.getOutputStream());
        clientListener = new ClientListener(this, receiverable);
    }

    public boolean isLogged() {
        return !getNickName().equals(DEFAULT_NAME);
    }

    public String getLobby() {
        return lobby;
    }

    public void setLobby(String lobby) {
        this.lobby = lobby;
    }

    public String getFullNameWithLobby() {
        return  "[" + lobby + "]" + nickName;
    }

    public String getNickName() {
        return ((nickName == null) || (socket.isClosed())) ? DEFAULT_NAME : nickName;
    }

    public boolean setNickName(String nick) {
        if((DEFAULT_NAME.equals(nick))
                || (nick == null)
                || (nick.length() < 1)
                || (nick.length() > 150)) {
            return false;
        }
        this.nickName = nick;
        return true;
    }

    public void startListener() {
        clientListener.start();
    }

    public String read() {
        try {
            return in.readUTF();
        } catch (IOException e) {
            close();
        }
        return null;
    }

    public synchronized void write(String message) {
        try {
            out.writeUTF(message);
        } catch (IOException e) {
            close();
        }
    }

    public void close() {
        clientListener.interrupt();
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        receiverable.onClientDisconnect(this);
        System.out.println("client disconnected");
    }
}
